package com.example.shopcatdemo;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Intent;
import android.graphics.PointF;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.example.shopcatdemo.adapter.ContentAdapter;
import com.example.shopcatdemo.adapter.LeftAdapter;
import com.example.shopcatdemo.adapter.ShopCartAdapter;
import com.example.shopcatdemo.bean.AllResutl;
import com.example.shopcatdemo.bean.ContentResult;
import com.example.shopcatdemo.bean.LeftResult;
import com.example.shopcatdemo.bean.ShopCartResult;
import com.example.shopcatdemo.sql.bean.ShopCartBean;
import com.example.shopcatdemo.sql.dao.ShopCartBeanDao;
import com.example.shopcatdemo.utils.AmountCalculationUtils;
import com.example.shopcatdemo.utils.SharePreferenceUtil;
import com.example.shopcatdemo.utils.StringUtils;
import com.example.shopcatdemo.view.shopcart.FakeAddImageView;
import com.example.shopcatdemo.view.shopcart.PointFTypeEvaluator;
import com.flipboard.bottomsheet.BottomSheetLayout;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class MainActivity extends AppCompatActivity {//implements SectionIndexer
    private static final String TAG = "MainActivity";
    /**
     * 上次第一个可见元素，用于滚动时记录标识。
     */
    private int lastFirstVisibleItem = -1;

    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout mSmartRefreshLayout;

    @BindView(R.id.main_layout)
    FrameLayout mainLayout;

    @BindView(R.id.bottomSheetLayout)
    BottomSheetLayout bottomSheetLayout;


    @BindView(R.id.image_cart)
    ImageView imageCart;
    @BindView(R.id.tv_number)
    TextView tvNumber;
    @BindView(R.id.frame_shop_cart)
    FrameLayout frameShopCart;

    @BindView(R.id.tv_money_symbol)
    TextView tvMoneySymbol;
    @BindView(R.id.tv_total_price)
    TextView tvTotalPrice;

    @BindView(R.id.btn_buy_now)
    Button btnBuyNow;

    @BindView(R.id.left_recyclerView)
    RecyclerView mLeftRecyclerView;

    private LeftAdapter mLeftAdapter;


    @BindView(R.id.tv_hover_title)
    TextView tvHoverTitle;
    @BindView(R.id.content_recyclerView)
    RecyclerView mContentRecyclerView;

    private ContentAdapter mContentAdapter;
    private LinearLayoutManager mLayoutManager;


    private ShopCartBeanDao shopCartBeanDao;
    private SharePreferenceUtil mPreferencesUtil;
    private float totalPrice;//总价格
    private int totalNumber;//总个数


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);

        mPreferencesUtil = SharePreferenceUtil.getInstance(this);
        mPreferencesUtil.setUserId("13245648435482855");


        initView();

        initListener();

        initData(strJson);
    }

    private void initView() {
        shopCartBeanDao = InitApplication.getDaoInstant().getShopCartBeanDao();

        mLeftRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mLeftAdapter = new LeftAdapter(null);
        mLeftRecyclerView.setAdapter(mLeftAdapter);

        mLayoutManager = new LinearLayoutManager(this);
        mContentRecyclerView.setLayoutManager(mLayoutManager);
        mContentAdapter = new ContentAdapter(null);
        mContentRecyclerView.setAdapter(mContentAdapter);

        totalPriceCalculation();


    }

    //private int currentPosition; //点击添加购物车，当前的位置
    //private boolean isAddShopCartSuccess = true;//是否加入成功购物车成功(从确认加入到动画执行结束)

    private void initListener() {

        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        initData(strJson);
                        mSmartRefreshLayout.finishRefresh();
                    }
                }, 2 * 1000);


            }
        });


        frameShopCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (tvNumber.getVisibility() == View.VISIBLE) {
                    List<ShopCartBean> shopCartBeans = shopCartBeanDao.queryBuilder()
                            .where(ShopCartBeanDao.Properties.User_id
                                    .eq(mPreferencesUtil.getUserId()))
                            .build().list();

                    showPopupWindow(shopCartBeans);
                }

            }
        });

        mLeftAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                updateMenuStatus(position);
                if (position == 0) {
                    //mLayoutManager.scrollToPosition(0);//测试发现这个，方法是不好的。
                    mLayoutManager.scrollToPositionWithOffset(0, 0);
                } else {
                    if (productBeanList != null && productBeanList.size() > 0) {
                        int scrollToPosition = 0;
                        for (int i = 0; i < position; i++) {
                            scrollToPosition += productBeanList.get(i).list.size() + 1;
                        }
                        Log.i(TAG, "onItemClick: scrollToPosition=" + scrollToPosition);
                        mLayoutManager.scrollToPositionWithOffset(scrollToPosition, 0);
                    }
                }
            }
        });

        mContentAdapter.setOnItemClickListener((adapter, view, position) -> {
            Log.i(TAG, "onItemClick: 商品详情跳转 position=" + position);
            startActivity(new Intent(MainActivity.this, SecondActivity.class));

        });


        mContentAdapter.setOnAnimShopClickListener(new ContentAdapter.OnAnimShopClickListener() {
            @Override
            public void onAddSuccess(View view, int count, int position) {

                ContentResult itemData = mContentAdapter.getItem(position);

                saveData(count, itemData);

                updateContentAdapter(itemData.getCount(), itemData.getProduct_id());

                startAnimation(view, imageCart);

            }

            @Override
            public void onDelSuccess(View view, int count, int position) {

                ContentResult itemData = mContentAdapter.getItem(position);

                saveData(count, itemData);

                updateContentAdapter(itemData.getCount(), itemData.getProduct_id());

                totalPriceCalculation();
            }
        });


        mContentRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == 0) {//解决滑动过快，firstVisibleItemPosition 没有被赋值，导致左边菜单项，状态设置不对的问题。
                    int firstVisibleItemPosition = mLayoutManager.findFirstVisibleItemPosition();
                    String strTitle = mContentResultList.get(firstVisibleItemPosition).getTitle();
                    Log.i(TAG, "onScrollStateChanged: firstVisibleItemPosition=" + firstVisibleItemPosition);
                    for (LeftResult leftResult : mLeftResultList) {
                        if (leftResult.name.equals(strTitle)) {
                            leftResult.isSelect = true;
                        } else {
                            leftResult.isSelect = false;
                        }
                    }
                    mLeftAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);

                int firstVisibleItemPosition = mLayoutManager.findFirstVisibleItemPosition();


                String strTitle = mContentResultList.get(firstVisibleItemPosition).getTitle();
                String strName = mContentResultList.get(firstVisibleItemPosition).getName();

                if (TextUtils.isEmpty(strName) && !TextUtils.isEmpty(strTitle)) {
                    //Log.i(TAG, "onScrolled: strTitle=" + strTitle + " firstVisibleItemPosition=" + firstVisibleItemPosition);

                    for (LeftResult leftResult : mLeftResultList) {
                        if (leftResult.name.equals(strTitle)) {
                            leftResult.isSelect = true;
                        } else {
                            leftResult.isSelect = false;
                        }
                    }
                    mLeftAdapter.notifyDataSetChanged();
                }


                //悬浮标题处理 实现
                hoverTitleDealWith(recyclerView, firstVisibleItemPosition);


            }
        });


    }

    /**
     * 刷新内容adapter
     */
    private void updateContentAdapter(int count, String productId) {
        // TODO: 2019/1/12 0012 这里后续优化，可以这样优化，相同商品的个数超过2个的再去刷新列表，否则就不要刷新列表啦

        //去遍历列表，发现商品id相同的，个数 都赋值一样的。
        for (ContentResult result : mContentResultList) {
            if (productId.equals(result.getProduct_id())) {
                result.setCount(count);
            }
        }
        if (count == 0) {
            //这样能保证动画效果能执行完毕，否则动画效果就会没有了。当然也可不做这样的处理，直接去刷新列表即可。
            new Handler().postDelayed(() -> mContentAdapter.notifyDataSetChanged(), 400);
        } else {
            mContentAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 说明：总个数的计算和总价格的计算
     * <p>
     * 添加购物车动画结束之后也调用这个方法
     */
    private void totalPriceCalculation() {
        totalNumber = 0;
        totalPrice = 0;

        List<ShopCartBean> shopCartBeans = shopCartBeanDao.queryBuilder().where(
                ShopCartBeanDao.Properties.User_id.eq(mPreferencesUtil.getUserId())
        ).build().list();

        if (shopCartBeans != null && shopCartBeans.size() > 0) {
            for (ShopCartBean shopCartBean : shopCartBeans) {
                totalNumber += shopCartBean.getQuantity();

                totalPrice = AmountCalculationUtils.addF(totalPrice + "",
                        AmountCalculationUtils.multiplyS(shopCartBean.getPrice() + "", shopCartBean.getQuantity() + ""));
            }
        }

        if (totalNumber == 0) {
            priceAndNumberHideDealWith();
        } else {
            tvMoneySymbol.setVisibility(View.VISIBLE);
            tvNumber.setVisibility(View.VISIBLE);
            tvNumber.setText(totalNumber + "");

            tvTotalPrice.setVisibility(View.VISIBLE);
            tvTotalPrice.setText(totalPrice + "");
        }
    }


    private void saveData(int count, ContentResult itemData) {
        //把保存数据的，从sql中查一下，是否已存在，如果查到了，就覆盖，否则生成新的主键，保存
        List<ShopCartBean> shopCartBeans = shopCartBeanDao.queryBuilder().where(
                ShopCartBeanDao.Properties.User_id.eq(mPreferencesUtil.getUserId())
                , ShopCartBeanDao.Properties.Product_id.eq(itemData.getProduct_id())
        ).build().list();

        if (count == 0) {
            if (shopCartBeans != null && shopCartBeans.size() > 0) {//删除的情况下,count才可能为0，肯定存在
                //由于业务的逻辑，这里根据User_id和Product_id查出的商品，肯定是就一个。
                //因为同一个用户下，只有一个唯一的商品id
                shopCartBeanDao.delete(shopCartBeans.get(0));
            }

        } else {
            ShopCartBean shopCartBean = new ShopCartBean();

            if (shopCartBeans != null && shopCartBeans.size() > 0) {//已存在
                //由于业务的逻辑，这里根据User_id和Product_id查出的商品，肯定是就一个。
                //因为同一个用户下，只有一个唯一的商品id
                shopCartBean.setIds(shopCartBeans.get(0).getIds());
            } else {//不存在
                shopCartBean.setIds(StringUtils.getUUID());
            }

            shopCartBean.setUser_id(mPreferencesUtil.getUserId());
            shopCartBean.setProduct_id(itemData.getProduct_id());
            shopCartBean.setProduct_name(itemData.getName());
            shopCartBean.setQuantity(itemData.getCount());
            shopCartBean.setInventory(itemData.getInventory());
            shopCartBean.setPrice(itemData.getShopprice());
            shopCartBeanDao.insertOrReplace(shopCartBean);
        }


    }

    /**
     * 总价格和总个数的隐藏处理
     */
    private void priceAndNumberHideDealWith() {
        tvNumber.setVisibility(View.GONE);
        tvNumber.setText("0");
        tvMoneySymbol.setVisibility(View.INVISIBLE);
        tvTotalPrice.setVisibility(View.GONE);
        tvTotalPrice.setText("0");
    }

    /**
     * 更新左边菜单类型的状态
     *
     * @param position
     */
    private void updateMenuStatus(int position) {
        List<LeftResult> dataList = mLeftAdapter.getData();
        for (int i = 0; i < dataList.size(); i++) {
            if (i == position) {
                dataList.get(i).isSelect = true;
            } else {
                dataList.get(i).isSelect = false;
            }
        }
        mLeftAdapter.notifyDataSetChanged();
    }

    /*底部弹框 购物车 相关 stat */

    private void showPopupWindow(List<ShopCartBean> shopCartBeans) {
        //if (bottomSheet == null) {
        View bottomSheet = createBottomSheetView(shopCartBeans);//底层视图初始化
        // }
        if (bottomSheetLayout.isSheetShowing()) {
            bottomSheetLayout.dismissSheet();
        } else {
            bottomSheetLayout.showWithSheetView(bottomSheet);
        }

    }

    private View createBottomSheetView(List<ShopCartBean> shopCartBeans) {
        View popupWindowView = LayoutInflater.from(this).inflate(R.layout.popupwindow_shopcart, (ViewGroup) this.getWindow().getDecorView(), false);
        TextView clearShopCart = (TextView) popupWindowView.findViewById(R.id.clear);
        RecyclerView mRecyclerView = (RecyclerView) popupWindowView.findViewById(R.id.goods_car_recyclerView);
        clearShopCart.setOnClickListener(v -> {
            //isClearShopCart = true;

            // TODO: 2018/11/28 这里不应该，是清空数据库，应该是把当前用户的数据给清空
            shopCartBeanDao.deleteAll();
            bottomSheetLayout.dismissSheet();

            priceAndNumberHideDealWith();

            for (ContentResult result : mContentResultList) {
                result.setCount(0);
            }
            mContentAdapter.notifyDataSetChanged();

        });
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        List<ShopCartResult> shopCartList = new ArrayList<>();
        ShopCartResult shopCartResult;
        for (ShopCartBean cartBean : shopCartBeans) {
            shopCartResult = new ShopCartResult(cartBean.getInventory(), cartBean.getQuantity());

            shopCartResult.setProduct_id(cartBean.getProduct_id());
            shopCartResult.setName(cartBean.getProduct_name());
            shopCartResult.setPrice(cartBean.getPrice());
            shopCartResult.setIds(cartBean.getIds());

            shopCartList.add(shopCartResult);
        }
        ShopCartAdapter shopCartAdapter = new ShopCartAdapter(shopCartList);//getCartData()
        mRecyclerView.setAdapter(shopCartAdapter);

        shopCartAdapter.setOnAnimShopClickListener(new ShopCartAdapter.OnAnimShopClickListener() {
            @Override
            public void onAddSuccess(View view, int count, int position) {
                updateSqlData(count, shopCartAdapter.getItem(position).getIds());
            }

            @Override
            public void onDelSuccess(View view, int count, int position) {
                updateSqlData(count, shopCartAdapter.getItem(position).getIds());

                if (count == 0) {
                    if (shopCartAdapter.getData() != null && shopCartAdapter.getData().size() > 1) {
                        shopCartAdapter.remove(position);
                    } else {
                        bottomSheetLayout.dismissSheet();
                    }
                }

            }
        });


        return popupWindowView;
    }


    /**
     * 更新数据库中数据
     */
    private void updateSqlData(int count, String ids) {
        ShopCartBean cartBean;
        if (count > 0) {
            cartBean = shopCartBeanDao.queryBuilder()
                    .where(ShopCartBeanDao.Properties.Ids.eq(ids))
                    .build()
                    .unique();
            cartBean.setQuantity(count);
            shopCartBeanDao.update(cartBean);

        } else {
            cartBean = shopCartBeanDao.queryBuilder()
                    .where(ShopCartBeanDao.Properties.Ids.eq(ids))
                    .build()
                    .unique();
            //cartBeanDao.deleteByKey(cartBean.getId());
            shopCartBeanDao.delete(cartBean);
        }

        //去 遍历 mContentResultList 列表，发现相同商品id的商品，个数都要更新，然后刷新列表
        updateContentAdapter(count, cartBean.getProduct_id());
       /* for (ContentResult contentResult : mContentResultList) {
            if (cartBean.getProduct_id().equals(contentResult.getProduct_id())) {
                contentResult.setCount(count);
            }
        }
        mContentAdapter.notifyDataSetChanged();*/


        //计算购物车中商品总价格方法。
        totalPriceCalculation();


    }


    /*底部弹框，购物车 相关 end */


    /**
     * 抛物线动画
     *
     * @param addView          动画开始的控件view
     * @param shoppingCartView 动画结束的控件view
     */
    private void startAnimation(View addView, View shoppingCartView) {
        int[] addLocation = new int[2];
        int[] cartLocation = new int[2];
        int[] recycleLocation = new int[2];

        addView.getLocationInWindow(addLocation);
        shoppingCartView.getLocationInWindow(cartLocation);
        mContentRecyclerView.getLocationInWindow(recycleLocation);


        PointF startP = new PointF();
        PointF endP = new PointF();
        PointF controlP = new PointF();

        //这个间距要和自定义AnimShopButton 中默认的一致
        float betweenCircle = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 34, getResources().getDisplayMetrics());
        startP.x = addLocation[0] + betweenCircle;

        //startP.x = addLocation[0];
        startP.y = addLocation[1] - recycleLocation[1];

        endP.x = cartLocation[0];
        endP.y = cartLocation[1] - recycleLocation[1];


        controlP.x = endP.x;
        controlP.y = startP.y;


        final FakeAddImageView fakeAddImageView = new FakeAddImageView(this);
        mainLayout.addView(fakeAddImageView);
        fakeAddImageView.setImageResource(R.drawable.ic_bug_cart);
        fakeAddImageView.getLayoutParams().width = getResources().getDimensionPixelSize(R.dimen.height_20);
        fakeAddImageView.getLayoutParams().height = getResources().getDimensionPixelSize(R.dimen.height_20);

        fakeAddImageView.setVisibility(View.VISIBLE);
        ObjectAnimator addAnimator = ObjectAnimator.ofObject(fakeAddImageView, "mPointF",
                new PointFTypeEvaluator(controlP), startP, endP);
        addAnimator.setInterpolator(new AccelerateInterpolator());
        addAnimator.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animator) {
                fakeAddImageView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animator animator) {
                fakeAddImageView.setVisibility(View.GONE);
                mainLayout.removeView(fakeAddImageView);

                totalPriceCalculation();//当动画结束之后，在更新数量

            }

            @Override
            public void onAnimationCancel(Animator animator) {

            }

            @Override
            public void onAnimationRepeat(Animator animator) {

            }
        });

        ObjectAnimator scaleAnimatorX = new ObjectAnimator().ofFloat(shoppingCartView, "scaleX", 0.6f, 1.0f);
        ObjectAnimator scaleAnimatorY = new ObjectAnimator().ofFloat(shoppingCartView, "scaleY", 0.6f, 1.0f);
        scaleAnimatorX.setInterpolator(new AccelerateInterpolator());
        scaleAnimatorY.setInterpolator(new AccelerateInterpolator());
        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(scaleAnimatorX).with(scaleAnimatorY).after(addAnimator);
        animatorSet.setDuration(800);
        animatorSet.start();
    }

    private List<LeftResult> mLeftResultList = new ArrayList<>();
    private List<ContentResult> mContentResultList = new ArrayList<>();

    private List<AllResutl.DataBean.ProductBean> productBeanList = new ArrayList<>();

    /**
     * 初始化数据，这里就是造点数据
     */
    private void initData(String strJsonDate) {
        mLeftResultList.clear();
        mContentResultList.clear();
        productBeanList.clear();

        Gson gson = new Gson();
        AllResutl allResutl = gson.fromJson(strJsonDate, AllResutl.class);

        if (allResutl.status == 1) {

            AllResutl.DataBean dataBean = allResutl.data;
            productBeanList = dataBean.product;

            if (productBeanList != null && productBeanList.size() > 0) {

                int i = 0;
                ContentResult contentResult;
                for (AllResutl.DataBean.ProductBean productBean : productBeanList) {
                    String name = productBean.name;


                    contentResult = new ContentResult(ContentResult.TITLE);

                    contentResult.setTitle(name);
                    mContentResultList.add(contentResult);


                    LeftResult leftResult = new LeftResult();
                    leftResult.name = productBean.name;

                    if (i == 0) {
                        leftResult.isSelect = true;
                    } else {
                        leftResult.isSelect = false;
                    }

                    mLeftResultList.add(leftResult);
                    i++;


                    List<AllResutl.DataBean.ProductBean.ListBean> listBean = productBean.list;

                    for (AllResutl.DataBean.ProductBean.ListBean bean : listBean) {
                        contentResult = new ContentResult(ContentResult.CONTENT);
                        contentResult.setProduct_id(bean.product_id);
                        contentResult.setName(bean.name);
                        contentResult.setShopprice(bean.shopprice);
                        contentResult.setInventory(bean.inventory);

                        //contentResult.setCount(0);

                        //这样做，是把左边的item和右边的item做出关联字段,目的是为了解决：
                        //列表滑动过快，firstVisibleItemPosition 没有被赋值，导致左边菜单项，状态设置不对的问题。
                        contentResult.setTitle(name);

                        mContentResultList.add(contentResult);
                    }


                }

            }

            //从购物车表中，查出商品，通过商品id与列表中的商品id一一比对
            // 符合的就把个数，赋值给列表中的个数
            List<ShopCartBean> shopCartBeans = shopCartBeanDao.queryBuilder().where(
                    ShopCartBeanDao.Properties.User_id.eq(mPreferencesUtil.getUserId())
            ).build().list();
            if (shopCartBeans != null && shopCartBeans.size() > 0) {
                for (ShopCartBean shopCartBean : shopCartBeans) {
                    for (ContentResult result : mContentResultList) {
                        if (shopCartBean.getProduct_id().equals(result.getProduct_id())) {
                            result.setCount(shopCartBean.getQuantity());
                        }
                    }
                }
            }


            mLeftAdapter.setNewData(mLeftResultList);
            mContentAdapter.setNewData(mContentResultList);


        } else {
            Log.i(TAG, "initData: allResutl=" + allResutl.msg);
        }

    }


    /**
     * 悬浮标题处理
     * <p>
     * 实现步骤描述：
     * （1）：要获取到列表中，第一个显示的item+1 的item的bean类，判断是否为菜单类型
     * 是的话，把该item的 position 赋值给一个临时变量 a
     * （2）：在滑动过程中，当 临时变量 a  等于 列表中第一个显示的item+1 的时候，
     * （3）：获取列表中（ View childView = recyclerView.getChildAt(0);）第一个view， 通过  childView.getBottom()
     * 实时获取item显示的距离
     * <p>
     * （4）：通过比较 item显示的距离 和 悬浮标题的高度，来动态设置 悬浮标题 移动 即可！
     *
     * @param recyclerView
     * @param firstVisibleItemPosition
     */
    private void hoverTitleDealWith(@NonNull RecyclerView recyclerView, int firstVisibleItemPosition) {

        //int section = getSectionForPosition(firstVisibleItemPosition);
        //int nextSection = getSectionForPosition(firstVisibleItemPosition + 1);
        //int nextSecPosition = getPositionForSection(+nextSection);

        int nextSection = 0;//下一个位置
        String strNextTitle = mContentResultList.get(firstVisibleItemPosition + 1).getTitle();
        String strNextName = mContentResultList.get(firstVisibleItemPosition + 1).getName();
        if (TextUtils.isEmpty(strNextName) && !TextUtils.isEmpty(strNextTitle)) {
            nextSection = firstVisibleItemPosition + 1;
        }

        //Log.i(TAG, "onScrolled: firstVisibleItemPosition=" + firstVisibleItemPosition + " lastFirstVisibleItem=" + lastFirstVisibleItem);
        if (firstVisibleItemPosition != lastFirstVisibleItem) {
            ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) tvHoverTitle.getLayoutParams();
            params.topMargin = 0;
            tvHoverTitle.setLayoutParams(params);

            tvHoverTitle.setText(mContentResultList.get(firstVisibleItemPosition).getTitle());

        }

        //Log.i(TAG, "onScrolled: nextSection="+nextSection+" nextSecPosition="+nextSecPosition);
        if (nextSection == firstVisibleItemPosition + 1) {
            View childView = recyclerView.getChildAt(0);
            if (childView != null) {
                int titleHeight = tvHoverTitle.getHeight();

                int bottom = childView.getBottom();//我认为这行代码，很关键。（获取顶部item 显示出来的高度）

                ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) tvHoverTitle.getLayoutParams();

                //Log.i(TAG, "onScrolled: bottom=" + bottom + " titleHeight=" + titleHeight);
                if (bottom < titleHeight) {

                    float pushedDistance = bottom - titleHeight;
                    params.topMargin = (int) pushedDistance;
                    tvHoverTitle.setLayoutParams(params);
                } else {
                    if (params.topMargin != 0) {
                        params.topMargin = 0;
                        tvHoverTitle.setLayoutParams(params);
                    }
                }
            }
        }
        lastFirstVisibleItem = firstVisibleItemPosition;
    }

    //模拟json数据
    private String strJson = "{\n" +
            "\t\"msg\": \"请求成功\",\n" +
            "\t\"status\": 1,\n" +
            "\t\"data\": {\n" +
            "\t\t\"product\": [{\n" +
            "\t\t\t\"label_img\": \"http://sq-files.wode369.com/sq-files/other/label/cuxiao.png\",\n" +
            "\t\t\t\"list\": [{\n" +
            "\t\t\t\t\"product_id\": \"3cf3fa3f5de54a4fa5ac98b01a1e850c\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"苹果\",\n" +
            "\t\t\t\t\"shopprice\": \"1.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"8d4528822f1f49889a64985d600d979e\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"2.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"b694faaee23d4fafaa0e8014dd33ad0a\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"3.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"df675b5760724ace879e6f22a2f312a0\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"4.01\"\n" +
            "\t\t\t}],\n" +
            "\t\t\t\"name\": \"促销\"\n" +
            "\t\t}, {\n" +
            "\t\t\t\"label_img\": \"http://sq-files.wode369.com/sq-files/other/label/cuxiao.png\",\n" +
            "\t\t\t\"list\": [{\n" +
            "\t\t\t\t\"product_id\": \"3cf3fa3f5de54a4fa5ac98b01a1e850c\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"苹果\",\n" +
            "\t\t\t\t\"shopprice\": \"1.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"4ec52417d8504749ac605408834c6366\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"0.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"4ec52417d8504749ac605408834c6377\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"0.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"4ec52417d8504749ac605408834c6388\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"0.01\"\n" +
            "\t\t\t}],\n" +
            "\t\t\t\"name\": \"优选\"\n" +
            "\t\t}, {\n" +
            "\t\t\t\"label_img\": \"http://sq-files.wode369.com/sq-files/other/label/cuxiao.png\",\n" +
            "\t\t\t\"list\": [{\n" +
            "\t\t\t\t\"product_id\": \"4ec52417d8504749ac605408834c6001\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"0.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"4ec52417d8504749ac605408834c6002\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"0.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"4ec52417d8504749ac605408834c6003\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"0.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"4ec52417d8504749ac605408834c6004\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"0.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"4ec52417d8504749ac605408834c6005\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"0.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"4ec52417d8504749ac605408834c6006\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"0.01\"\n" +
            "\t\t\t}, {\n" +
            "\t\t\t\t\"product_id\": \"4ec52417d8504749ac605408834c6007\",\n" +
            "\t\t\t\t\"inventory\": 45,\n" +
            "\t\t\t\t\"name\": \"皇家佰瑞特橄榄油（1L)\",\n" +
            "\t\t\t\t\"shopprice\": \"0.01\"\n" +
            "\t\t\t}],\n" +
            "\t\t\t\"name\": \"蔬菜\"\n" +
            "\t\t}]\n" +
            "\t}\n" +
            "}";


}



/*@Override
    public Object[] getSections() {
        return new Object[0];
    }

    //通过该项的位置，获得所在分类组的索引号
    @Override
    public int getPositionForSection(int sectionIndex) {
        Log.i(TAG, "ypk getPositionForSection: " + sectionIndex);


        return sectionIndex;
    }

    // 根据分类列的索引号获得该序列的首个位置
    @Override
    public int getSectionForPosition(int position) {
        Log.i(TAG, "ypk  getSectionForPosition: " + position);
        //int size = productBeanList.get(position).list.size();
        String strTitle = mContentResultList.get(position).title;
        String strName = mContentResultList.get(position).name;
        if (TextUtils.isEmpty(strName) && !TextUtils.isEmpty(strTitle)) {
            return position;
        } else {
            return 0;
        }

    }*/